﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Threading.Tasks;


namespace WinForm_Halcon_ChePai
{
    public class SerialPortHelper
    {
        //引用串口通信的对象
        SerialPort serialPort = new SerialPort();
        static SerialPortHelper(){}
        private SerialPortHelper(){
            //设置参数
            serialPort.PortName = "COM2";
            //设置波特率
            serialPort.BaudRate = 9600;
            //设置校验位
            serialPort.Parity = Parity.None;
            //设置数据位
            serialPort.DataBits = 8;
            //设置停止位
            serialPort.StopBits = StopBits.One;
        }
        private static readonly SerialPortHelper _instance = new SerialPortHelper();
        public static SerialPortHelper Instance
        {
            get {  return _instance; }
        }


        public bool Send(string data)
        {
            bool flag = false;
            try
            {
                //打开串口
                if (!serialPort.IsOpen)
                {
                    serialPort.Open();
                }
                //发送数据
                if (serialPort.IsOpen)
                {
                    serialPort.Write(data);
                    serialPort.Close();
                    flag = true;
                }
            }
            catch (Exception)
            {
                flag=false;
                throw;
            }
            return flag;
        }

        public string ReceiveData()
        {
            string data = null;
            serialPort.Open();
            if (serialPort.IsOpen)
            {
                byte[] bytes = new byte[1024];
                int lenght = serialPort.Read(bytes, 0, bytes.Length);
                data = System.Text.Encoding.UTF8.GetString(bytes, 0, lenght);
                serialPort.Close();
            }
            return data;
        }


    }
}
